package com.roc.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTime {
	/**
	 * 常用的日期时间格式
	 */
	private static SimpleDateFormat defaultFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	public static String getNow(String formatStr) {
		Date date = new Date();
		try {
			SimpleDateFormat format = new SimpleDateFormat(formatStr);
			return format.format(date).toString();
		} catch (Exception e) {
			return defaultFormat.format(date);
		}
	}

	public static String g_DateTime_SystemLastDay() {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(
				"yyyyMMdd");
		Calendar calendar = Calendar.getInstance();

		calendar.add(Calendar.DAY_OF_MONTH, -2);

		return df.format(calendar.getTime());

	}

	public static String g_DateTime_SystemYesDay() {
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(
				"yyyyMMdd");
		Calendar calendar = Calendar.getInstance();

		calendar.add(Calendar.DAY_OF_MONTH, -1);

		return df.format(calendar.getTime());

	}

	/**
	 * 获取指定日期前后 N天的日期
	 * 
	 * @param date
	 * @param format
	 * @param len
	 * @return
	 */
	public static String getDay(String date, String format, int len) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			Calendar cal = Calendar.getInstance();
			cal.setTime(sdf.parse(date));
			cal.add(Calendar.DATE, len);
			return sdf.format(cal.getTime());
		} catch (Exception e) {
			return date;
		}
	}
	
	
	/**
	 *  获取前月的第一天
	 * @return
	 */
	public static String getFirstDayOfLastMonth() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

		// 获取前月的第一天
		Calendar cal_1 = Calendar.getInstance();// 获取当前日期
		cal_1.add(Calendar.MONTH, -1);
		cal_1.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		String firstDay = format.format(cal_1.getTime());
		return firstDay;
	}

	/**
	 * 获取前月的最后一天
	 * @return
	 */
	public static String getLastDayOfLastMonth() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

		// 获取前月的最后一天
		Calendar cale = Calendar.getInstance();
		cale.set(Calendar.DAY_OF_MONTH, 0);// 设置为1号,当前日期既为本月第一天
		String lastDay = format.format(cale.getTime());
		return lastDay;
	}

	public static void main(String[] args) {
		String a = g_DateTime_SystemYesDay();
		System.out.println(a);
		System.out.println("a1:"+getLastDayOfLastMonth());
	}
}
